package com.pfzy.lib.net;

import com.pfzy.lib.net.lifecycle.ILifeCycle;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class ObservableProxy<T> {
//    private static final int MAX_RETRY_TIMES = 10;
//    private static final int MIN_RETRY_TIMES = 1;
    private Observable<T> mObservable;

    public ObservableProxy(Observable<T> observable) {
        this.mObservable = observable;
    }

    public Observable<T> bind(ILifeCycle key) {
        if (key == null) {
            throw new RuntimeException("the key to bind lifecycle can not be null");
        }
        return this.mObservable.takeUntil(key.getLifeCycleObservable().get());
    }

//    public ObservableProxy<T> retry(int time) {
//        if (time >= MIN_RETRY_TIMES) {
//            if (time > MAX_RETRY_TIMES) {
//                time = MAX_RETRY_TIMES;
//            }
//            final int finalTime = time;
//            this.mObservable = this.mObservable.retry(new Func2<Integer, Throwable, Boolean>() {
//                @Override
//                public Boolean call(Integer integer, Throwable throwable) {
//                    return integer.intValue() <= finalTime && ObservableProxy.this.belongRetryThrowable(throwable);
//                }
//            });
//        }
//        return this;
//    }
//
//    public boolean belongRetryThrowable(Throwable throwable) {
//        return (throwable instanceof SocketTimeoutException) || (throwable instanceof ConnectTimeoutException);
//    }

    public Observable<T> origin() {
        return this.mObservable;
    }

    public void subscribe(Observer<? super T> observer) {
        this.mObservable.subscribe(observer);
    }

    public static <T> ObservableProxy<T> createProxy(Observable<T> observable) {
        return new ObservableProxy<>(
                observable
                        .subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
        );
    }
}
